package base.transporte;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class FilePackager {
	FileInputStream inFile;
	boolean isEOF;

	public FilePackager(String fileName) throws FileNotFoundException {
		File file = new File(fileName);
		isEOF = false;
		if (file.exists()) {
			inFile = new FileInputStream(fileName);
		} else {
			throw new FileNotFoundException();
		}
	}
	
	public FilePackager(File file) throws FileNotFoundException {
		this.inFile = new FileInputStream(file);
		isEOF = false;
		
	}

	public SRPacket getNextPacket() {
		SRPacket retorno = null;
		byte[] bytes = new byte[Constantes.dataMax];
		int bytesLidos = 0;
		
		if (!isEOF) {
			try {
				bytesLidos = inFile.read(bytes, 0, Constantes.dataMax);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if (bytesLidos == -1) {
			bytes = "EOF".getBytes();
			isEOF = true;
			try {
				inFile.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} else if (bytesLidos < Constantes.dataMax) {
			byte[] bytes_menor = new byte[bytesLidos];
			System.arraycopy(bytes, 0, bytes_menor, 0, bytesLidos);
			bytes = bytes_menor;
		}

		try {
			retorno = new SRPacket(0, bytes);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return retorno;
	}

	public boolean isEOF() {
		return this.isEOF;
	}
}
